const jwt = require("jsonwebtoken")

const { secret } = require("../config/config")

module.exports = (req, res, next) => {
  // 获取头信息中的token
  const token = req.get("Authorization")
  const userRole = req.get("userRole")
  console.log("token---", token)
  console.log("userRole---", userRole)
  if(userRole==='visitor') {
    next()
  }else {
    if (!token) {
      res.json({
        code: 5001,
        msg: "您还没有登录",
        data: null
      })
      return
    }
  
    jwt.verify(token, secret, (err, data) => {
      if (err) {
        res.json({
          code: 5002,
          msg: "登录过期",
          data: null
        })
        return
      }
      // 保存用户信息
      req.user = data
  
      next()
    })
  }
}
